﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using System.Data;
using Atom.Entity;
using System.Data.Common;
using Atom.Utility.Data;
using System.Configuration;

namespace Atom.Interface.DataAccess
{
    public class FoxProDataAccess : IDataAccess
    {
        private static readonly string ConnectString = "Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" +( ConfigurationManager.AppSettings["DataPath"] == "" ? "F:\babf\\" : ConfigurationManager.AppSettings["DataPath"] )+ ";Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=YES";
        //string em=ConfigurationManager.AppSettings["DataPath"]==""?"F:\babf\":(ConfigurationManager.AppSettings["DataPath"]) ;

        public FoxProDataAccess()
        {

        }
        public int OpenConn()
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            string table = @"D:\babf\";
            string connStr = @"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" + table + ";Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=NO";
            conn.ConnectionString = connStr;
            conn.Open();


            OdbcCommand cmd = new OdbcCommand();
            cmd.Connection = conn;

            // string sql = "update " + table + " set other='2',rate=1.014 ";

            string sql = @"
                            INSERT INTO BAF1
                                       (BAZA01
                                       ,BAF102
                                       ,BAF103
                                       ,BAF104
                                       ,BAF105
                                       ,BAF106
                                       ,BAF107
                                       ,BAF111
                                       ,BAF112)
                                 VALUES('1',1,'1','1','1','1','1','1','1')
                            ";

            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();


            //sql = @"select * from BAF1" ;
            //OdbcDataAdapter da = new OdbcDataAdapter(sql, conn);
            //DataTable dt = new DataTable();
            //da.Fill(dt);

            //return dt.Rows.Count;

            return 1;

            //this.GridView1.DataSource = dt.DefaultView;
            //this.GridView1.DataBind(); 
        }


        #region IDataAccess 成员

        public int GetCount()
        {
            return 1;
        }

        #endregion

        #region IDataAccess 成员




        public Atom.Entity.SqlExecuteResult Delete(object id)
        {
            throw new NotImplementedException();
        }

        public  List<T> ExecuteListEntity<T>(DbCommand cmd) where T : class, new()
        {
            List<T> list = new List<T>();
            using (System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(ConnectString))
            {
                conn.Open();
                OdbcCommand odbcCmd = new OdbcCommand();
                odbcCmd.CommandText = cmd.CommandText;
                odbcCmd.CommandType = cmd.CommandType;

                foreach (DbParameter item in cmd.Parameters)
                {
                    odbcCmd.Parameters.Add(item.ParameterName);
                    odbcCmd.Parameters[item.ParameterName].DbType = item.DbType;
                    odbcCmd.Parameters[item.ParameterName].Value = item.Value;
                }
                cmd.Connection = conn;
                IDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    //T local = Activator.CreateInstance<T>();
                    //action(local, reader);

                    DynamicBuilder<T> builder = DynamicBuilder<T>.CreateBuilder(reader);
                    T local = builder.Build(reader);

                    list.Add(local);
                }

            }
            return list;
        }

        public Atom.Entity.SqlExecuteResult ExcuteSingleEntity(System.Data.Common.DbCommand cmd, System.Data.Common.DbTransaction trans)
        {
            return ExecuteCommands(new List<DbCommand>() { cmd }, trans);
        }

        public Atom.Entity.SqlExecuteResult ExecuteCommands(List<System.Data.Common.DbCommand> commands, System.Data.Common.DbTransaction tran)
        {
            SqlExecuteResult result = new SqlExecuteResult();
          
            using (System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(ConnectString))
            {
                conn.Open();
               OdbcTransaction  trans = conn.BeginTransaction();
                try
                {
                    foreach (var command in commands)
                    {
                        OdbcCommand odbcCmd = new OdbcCommand();
                        odbcCmd.CommandText = command.CommandText;
                        odbcCmd.CommandType = command.CommandType;

                        odbcCmd.Connection = conn;
                        odbcCmd.Transaction = trans;
                        
                        odbcCmd.ExecuteNonQuery();
                        
                    }
                    result.Success = true;
                    trans.Commit();
                }
                catch (Exception e)
                {
                    result.Success = true;
                    result.Exception = e;
                    trans.Rollback();
                }
                finally
                {
                    conn.Close();
                }

            }
            return result;
        }

        #endregion

        #region IDataAccess 成员


        public bool Exit()
        {
            throw new NotImplementedException();
        }

        public SqlExecuteResult ExecuteCommand(DbCommand cmd, DbTransaction trans)
        {
            return ExecuteCommands(new List<DbCommand>() { cmd }, trans);
        }

        public bool CheckExist(string tableName, string columnName, string mapperValue, string idColumnName, DbTransaction trans)
        {
            bool isExist = false;
            using (System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(ConnectString))
            {
                conn.Open();
                OdbcCommand cmd = new OdbcCommand();
                cmd.Connection = conn;

                string sql = string.Format("SELECT {2} FROM {0} WHERE {1} = @val "
                  , tableName, columnName, idColumnName);

                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("val", OdbcType.VarChar, 50, mapperValue);
                OdbcDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    isExist = true;
                }
            }

            return isExist;
        }

        #endregion
    }
}
